package com.fufan.mtsaas.modules.sysmgr.hrsys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
//import com.fufan.mtsaas.modules.sysmgr.dao.hrpymodule.PYempWagesDao;
//import com.fufan.mtsaas.modules.sysmgr.dao.hrpymodule.PYmonthlyLockDao;
import com.fufan.mtsaas.constant.RedisKeyConstant;
import com.fufan.mtsaas.constant.SystemConstant;
import com.fufan.mtsaas.modules.base.log.bo.request.LogSaveRequest;
import com.fufan.mtsaas.modules.base.log.service.TSysLogSvc;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.common.bo.response.ResultStandard;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.dao.TSysParamDao;
import com.fufan.mtsaas.modules.sysmgr.common.tocken.LoginTokenBO;
import com.fufan.mtsaas.modules.sysmgr.hrsys.bo.request.LoginRequest;
import com.fufan.mtsaas.modules.sysmgr.hrsys.bo.response.HRUserInfo;
import com.fufan.mtsaas.modules.sysmgr.hrsys.dao.SYGroupMenuInfoDao;
import com.fufan.mtsaas.modules.sysmgr.hrsys.dao.SYLOGDao;
import com.fufan.mtsaas.modules.sysmgr.hrsys.model.SYLOG;
import com.fufan.mtsaas.modules.sysmgr.hrsys.service.HRLoginUserSvc;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupMenuInfo;
import com.fufan.mtsaas.modules.sysmgr.sygroup.dao.SYgroupDeptDao;
import com.fufan.mtsaas.modules.sysmgr.sygroup.service.SYgroupHSvc;
import com.fufan.mtsaas.modules.sysmgr.symenu.bo.response.SYMenuItem;
import com.fufan.mtsaas.modules.sysmgr.symenu.bo.response.SYMenuSubItem;
import com.fufan.mtsaas.modules.sysmgr.symenu.bo.response.SYMenuSubTitle;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SYmenuDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.model.SYmenu;
import com.fufan.mtsaas.modules.sysmgr.syuser.dao.SYuserDao;
import com.fufan.mtsaas.modules.sysmgr.syuser.model.SYuser;
import com.fufan.mtsaas.modules.base.company.dao.TCompanyPurchaseDao;
import com.fufan.mtsaas.modules.base.company.model.TCompanyPurchase;
import com.fufan.mtsaas.tools.AESTool;
import com.fufan.mtsaas.tools.PasswordDigest;
import com.fufan.mtsaas.util.DateFormatTool;
import com.fufan.mtsaas.util.JwtUtil;
import com.fufan.mtsaas.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 登录登出服务实现类
 *
 * @auther Liby
 * @create 2019-09-15
 * */
@Service(value = "hrLoginUserSvcImpl")
@Slf4j
@Primary
public class HRLoginUserSvcImpl implements HRLoginUserSvc {

    @Autowired
    private SYuserDao sYuserDao;
    @Autowired
    private SYGroupMenuInfoDao hrGroupMenuInfoDao;
    @Autowired
    private SYgroupDeptDao sYgroupDeptDao;
//    @Autowired
//    private SYgroupScriptDao sYgroupScriptDao;
    @Autowired
    private SYmenuDao sYmenuDao;
    @Autowired
    private SYgroupHSvc sYgroupHSvc;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // Liby 2019-12-14
//    @Autowired
//    private PYempWagesDao pYempWagesDao;
//
//    @Autowired
//    private SyexptempSvc expService;

    // Liby 2020-05-12
    @Autowired
    private SYLOGDao sylogDao;

//    @Autowired
//    private SYLog logService;

    @Value("${COMPANY_CD}")
    private  String COMPANY_CODE;
    @Autowired
    private TSysLogSvc tSysLogSvc;
    @Autowired
    private TCompanyPurchaseDao tCompanyPurchaseDao;
//    @Autowired
//    private PYmonthlyLockDao entitymLockDao;

    @Autowired
    private TSysParamDao tsParamDao;

    @Autowired
    private ParamUtil paramUtil;

    /**
     * 登录（通过用户信息）
     */
    @Override
    public Result<HRUserInfo> loginCheckByUser(LoginRequest map) {
        RequestPojo requestPojo = ParamUtil.doChange();
        log.debug("HRLoginUserSvcImpl.loginCheck map {}", map);
        Result msg = new Result();
        List<HRUserInfo> res = new ArrayList<>();
        Page page = new Page();
        HRUserInfo userInfo = new HRUserInfo();
        String UserID = map.getUserID();

        int loginType = map.getLoginType();
        if (Objects.isNull(loginType)) {
            loginType = 0;
        }

        /**
         * 验证数据
         * */
        if (StringUtils.isEmpty(UserID)) {
            msg.setResStatus("E1002   ");
            msg.setResMsg("数据验证不通过！");
            return msg;
        }

        //员工编号
        HashMap<String, String> hsData = new HashMap();
        hsData.put("EmpNo", UserID);
        try {
            hsData.put("EmpNoUserID", AESTool.encrypt(UserID));
        } catch (Exception ex) {
//            hsData.put("UserID", UserID);
        }
//        String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +UserID);
//        hsData.put("id", userRedisId);
//        if(StringUtils.isEmpty(UserID)){
//            msg.setResStatus("E1002");
//            msg.setResMsg("用户不存在");
//            return msg;
//        }
        List<SYuser> sYuser = sYuserDao.selectList(page, hsData);
        if (null == sYuser || sYuser.size() == 0) {
            msg.setResStatus("E1002");
            msg.setResMsg("用户数据不存在，验证不通过！");
            return msg;
        }
        TCompanyPurchase tCompanyPurchase = tCompanyPurchaseDao.queryByOrder(sYuser.get(0).getCompanyID());
        if (tCompanyPurchase == null || tCompanyPurchase.getIsEnabled() == null || tCompanyPurchase.getIsEnabled() == 1) {
            msg.setResStatus(ResStatus.STATUS_PURCHASE_OUT_OF_TIME);
            msg.setResMsg(ResStatus.STATUS_PURCHASE_OUT_OF_TIME_MSG);
            return msg;
        }
        //更新登录时间
        sYuser.get(0).setLoginTime(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        sYuser.get(0).setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        sYuserDao.updateRecords(sYuser.get(0));

        /**
         * 验证密码是否正确
         * */
        String pass = "";
        try {
            pass = AESTool.encrypt(map.getPassword());
        } catch (Exception ex) {
            msg.setResStatus("E1002");
            msg.setResMsg("密码验证不通过！");
            return msg;
        }

        if (loginType == 1 && !pass.equals(sYuser.get(0).getPassword())) {
            msg.setResStatus("E1002");
            msg.setResMsg("用户或密码验证不通过！");
            return msg;
        }

        if (!StringUtils.isEmpty(sYuser.get(0).getVldFG()) && !sYuser.get(0).getVldFG().equalsIgnoreCase("0")) {
            msg.setResStatus("E1002");
            msg.setResMsg("用户无效，数据验证不通过！");
            return msg;
        }

        userInfo.setId(sYuser.get(0).getId());
        userInfo.setCompanyID(sYuser.get(0).getCompanyID());
        userInfo.setEmpNo(sYuser.get(0).getEmpNo());
        userInfo.setName(sYuser.get(0).getName());
        userInfo.setUserGroupID(sYuser.get(0).getUserGroupID());
        userInfo.setGroupName(sYuser.get(0).getUserGroupID());
        userInfo.setMailAddress(sYuser.get(0).getMailAddress());
        userInfo.setNote(sYuser.get(0).getNote());
        userInfo.setPhoneNo(sYuser.get(0).getPhoneNo());
        userInfo.setCheckMAC(sYuser.get(0).getCheckMAC());
        userInfo.setMACID(sYuser.get(0).getMACID());
        userInfo.setVldFG(sYuser.get(0).getVldFG());
        userInfo.setExclusiveFG(sYuser.get(0).getExclusiveFG());
        if (Objects.nonNull(sYuser.get(0).getUserID())) {
            try {
                userInfo.setUserID(AESTool.decrypt(sYuser.get(0).getUserID()));
            } catch (Exception e) {
            }
        }
        PasswordDigest passwordDigest = new PasswordDigest();
//        GroupDetailQueryRequest groupDetailQueryRequest = new GroupDetailQueryRequest();
//        groupDetailQueryRequest.setId(Long.valueOf(sYuser.get(0).getUserGroupID()));
//        List<RoleDetailRequest> roleDetailRequestList = new ArrayList<>();
//        if(groupDetailQueryRequest.getId() != null){
////            try {
//                roleDetailRequestList = sYgroupHSvc.doQueryDetail(groupDetailQueryRequest,requestPojo).getResData().getRecords();
////            }catch (Exception e){
////                msg.setResStatus(ResStatus.STATUS_ON_AUTH_NULL);
////                msg.setResMsg(ResStatus.STATUS_ON_AUTH_NULL_MSG);
////                return msg;
////            }
//        }
//        userInfo.setRoleDetailRequestList(roleDetailRequestList);
//        userInfo.setPassword(passwordDigest.encode(sYuser.get(0).getPassword()));

//        hsData = new HashMap();
//        hsData.put("CompanyID", CompanyID);
//        hsData.put("GroupID", userInfo.getUserGroupID());
//        List<SYGroupMenuInfo> hrGroupMenuInfoList = null;
//        hrGroupMenuInfoList = hrGroupMenuInfoDao.selectList(page, hsData);
//        userInfo.setSYgroupMenuList(hrGroupMenuInfoList);

//        List<SYGroupDeptInfo> sYgroupDeptList = null;
//        sYgroupDeptList = sYgroupDeptDao.selectList(page, hsData);
//        userInfo.setSYgroupDeptList(sYgroupDeptList);

        //items结构
//        List<SYMenuItem> sYMenuItem = new ArrayList<>();
//        sYMenuItem = this.makeMenuItems(sYMenuItem, hrGroupMenuInfoList);
//        userInfo.setItems(sYMenuItem);
//
//        log.debug("HRLoginUserSvcImpl.loginCheck userInfo {}", userInfo);

        LoginTokenBO loginTokenBO = new LoginTokenBO();

        if (Objects.nonNull(userInfo.getUserID())) {
            try {
                loginTokenBO.setUserId(AESTool.decrypt(userInfo.getUserID()));
            } catch (Exception e) {
                e.printStackTrace();
                loginTokenBO.setUserId(userInfo.getUserID());

            }
        } else {
            loginTokenBO.setUserId(userInfo.getEmpNo());
        }
        loginTokenBO.setSysId(String.valueOf(sYuser.get(0).getId()));
        loginTokenBO.setUserName(userInfo.getName());
        loginTokenBO.setAppKey("erthetitrjeoitjeotjeo");
        loginTokenBO.setCompanyId(userInfo.getCompanyID());
        loginTokenBO.setRoleId(userInfo.getUserGroupID());
        userInfo.setToken(JwtUtil.createToken(loginTokenBO));
        try {
            stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_TOKEN + ":" + userInfo.getCompanyID() + ":" + loginTokenBO.getUserId(), userInfo.getToken(), 60, TimeUnit.MINUTES);
        } catch (Exception e) {

        }

        userInfo.setShortName(paramUtil.getTSysParam("HOSPITAL_NAME"));
        userInfo.setDescName(paramUtil.getTSysParam("HOSPITAL_DESCRIPTION"));

        res.add(userInfo);
        page.setRecords(res);
        msg.setResStatus(SystemConstant.UDI_SUCCESSFUL_EXECUTION);
        msg.setResMsg("登录成功");
        msg.setResData(page);
        //更新登录时间
        log.debug("HRLoginUserSvcImpl.loginCheck msg {}", msg);

        try {
            LogSaveRequest logSaveRequest = new LogSaveRequest();
            logSaveRequest.setRelatedId(0L);
            logSaveRequest.setRelatedType("login");
            logSaveRequest.setLogTitle("登录");
            logSaveRequest.setLogContent("用户名称：" + userInfo.getName());
            logSaveRequest.setOperateTime(new Date());
            logSaveRequest.setOperateType("登录");
            logSaveRequest.setOperateStatus("成功");
            requestPojo.setCustId(userInfo.getCompanyID());
            tSysLogSvc.doSaveLogin(logSaveRequest, requestPojo);
        } catch (Exception e) {
            log.error("登录错误" + e.getMessage());
        }
        return msg;
    }

    /**
     * 获取系统参数
     *
     * @param paramName
     * @return
     */
//    private String getTSysParam(String paramName) {
//        String retVal = null;
//        TSysParam tsParam = new TSysParam();
//        tsParam.setParamName(paramName);
//        try {
//            TSysParam info = tsParamDao.selectOne(tsParam);
//            if (Objects.nonNull(info)) {
//                retVal = info.getParamValue();
//            }
//        } catch (Exception e) {
//
//        }
//        return retVal;
//    }

    /**
     * 登录（手机号码）
     * */
    @Override
    public Result<HRUserInfo> loginCheck(LoginRequest map, @ApiIgnore HttpSession session) {
        RequestPojo requestPojo = ParamUtil.doChange();
        log.debug("HRLoginUserSvcImpl.loginCheck map {}", map);
        Result msg = new Result();
        List<HRUserInfo>  res = new ArrayList<>();
        Page page = new Page();
        HRUserInfo userInfo = new HRUserInfo();
        String UserID = map.getUserID();

        int loginType = map.getLoginType();
        if (Objects.isNull(loginType)) {
            loginType = 0;
        }

        /**
         * 验证数据
         * */
        if(StringUtils.isEmpty(UserID)){
            msg.setResStatus("E1002   ");
            msg.setResMsg("数据验证不通过！");
            return msg;
        }

        HashMap<String, String> hsData = new HashMap();
       // hsData.put("UserID", UserID);
        String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +UserID);
        hsData.put("id", userRedisId);
        if(StringUtils.isEmpty(userRedisId)){
            msg.setResStatus("E1002");
            msg.setResMsg("用户不存在");
            return msg;
        }
        List<SYuser> sYuser = sYuserDao.selectList(page, hsData);
        if(null == sYuser || sYuser.size() == 0) {
            msg.setResStatus("E1002");
            msg.setResMsg("数据验证不通过！");
            return msg;
        }
        TCompanyPurchase tCompanyPurchase  = tCompanyPurchaseDao.queryByOrder(sYuser.get(0).getCompanyID());
        if(tCompanyPurchase == null || tCompanyPurchase.getIsEnabled() == null || tCompanyPurchase.getIsEnabled() == 1){
            msg.setResStatus(ResStatus.STATUS_PURCHASE_OUT_OF_TIME);
            msg.setResMsg(ResStatus.STATUS_PURCHASE_OUT_OF_TIME_MSG);
            return msg;
        }
        //更新登录时间
        sYuser.get(0).setLoginTime(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        sYuser.get(0).setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        sYuserDao.updateRecords(sYuser.get(0));

//        /**
//         * 验证密码是否正确
//         * */
//        if(loginType == 1 && !map.getPassword().equals(sYuser.get(0).getPassword())){
//            msg.setResStatus("E1002");
//            msg.setResMsg("数据验证不通过！");
//            return msg;
//        }

        if(!StringUtils.isEmpty(sYuser.get(0).getVldFG()) && !sYuser.get(0).getVldFG().equalsIgnoreCase("0")){
            msg.setResStatus("E1002");
            msg.setResMsg("用户无效，数据验证不通过！");
            return msg;
        }

        userInfo.setId(sYuser.get(0).getId());
        userInfo.setCompanyID(sYuser.get(0).getCompanyID());
        userInfo.setEmpNo(sYuser.get(0).getEmpNo());
        userInfo.setName(sYuser.get(0).getName());
        userInfo.setUserGroupID(sYuser.get(0).getUserGroupID());
        userInfo.setGroupName(sYuser.get(0).getUserGroupID());
        userInfo.setMailAddress(sYuser.get(0).getMailAddress());
        userInfo.setNote(sYuser.get(0).getNote());
        userInfo.setPhoneNo(sYuser.get(0).getPhoneNo());
        userInfo.setCheckMAC(sYuser.get(0).getCheckMAC());
        userInfo.setMACID(sYuser.get(0).getMACID());
        userInfo.setVldFG(sYuser.get(0).getVldFG());
        userInfo.setExclusiveFG(sYuser.get(0).getExclusiveFG());
        if (Objects.nonNull(sYuser.get(0).getUserID())) {
            try {
                userInfo.setUserID(AESTool.decrypt(sYuser.get(0).getUserID()));
            } catch (Exception e) {
            }
        }
        PasswordDigest passwordDigest = new PasswordDigest();
//        GroupDetailQueryRequest groupDetailQueryRequest = new GroupDetailQueryRequest();
//        groupDetailQueryRequest.setId(Long.valueOf(sYuser.get(0).getUserGroupID()));
//        List<RoleDetailRequest> roleDetailRequestList = new ArrayList<>();
//        if(groupDetailQueryRequest.getId() != null){
////            try {
//                roleDetailRequestList = sYgroupHSvc.doQueryDetail(groupDetailQueryRequest,requestPojo).getResData().getRecords();
////            }catch (Exception e){
////                msg.setResStatus(ResStatus.STATUS_ON_AUTH_NULL);
////                msg.setResMsg(ResStatus.STATUS_ON_AUTH_NULL_MSG);
////                return msg;
////            }
//        }
//        userInfo.setRoleDetailRequestList(roleDetailRequestList);
//        userInfo.setPassword(passwordDigest.encode(sYuser.get(0).getPassword()));

//        hsData = new HashMap();
//        hsData.put("CompanyID", CompanyID);
//        hsData.put("GroupID", userInfo.getUserGroupID());
//        List<SYGroupMenuInfo> hrGroupMenuInfoList = null;
//        hrGroupMenuInfoList = hrGroupMenuInfoDao.selectList(page, hsData);
//        userInfo.setSYgroupMenuList(hrGroupMenuInfoList);

//        List<SYGroupDeptInfo> sYgroupDeptList = null;
//        sYgroupDeptList = sYgroupDeptDao.selectList(page, hsData);
//        userInfo.setSYgroupDeptList(sYgroupDeptList);

        //items结构
//        List<SYMenuItem> sYMenuItem = new ArrayList<>();
//        sYMenuItem = this.makeMenuItems(sYMenuItem, hrGroupMenuInfoList);
//        userInfo.setItems(sYMenuItem);
//
//        log.debug("HRLoginUserSvcImpl.loginCheck userInfo {}", userInfo);

        LoginTokenBO loginTokenBO = new LoginTokenBO();
        try {
            loginTokenBO.setUserId(AESTool.decrypt(userInfo.getUserID()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        loginTokenBO.setSysId(String.valueOf(sYuser.get(0).getId()));
        loginTokenBO.setUserName(userInfo.getName());
        loginTokenBO.setAppKey("erthetitrjeoitjeotjeo");
        loginTokenBO.setCompanyId(userInfo.getCompanyID());
        loginTokenBO.setRoleId(userInfo.getUserGroupID());
        userInfo.setToken(JwtUtil.createToken(loginTokenBO));
        try {
            stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_TOKEN + ":" + userInfo.getCompanyID() + ":"+ loginTokenBO.getUserId(),userInfo.getToken(),60, TimeUnit.MINUTES);
        }catch (Exception e){

        }

        userInfo.setShortName(paramUtil.getTSysParam("HOSPITAL_NAME"));
        userInfo.setDescName(paramUtil.getTSysParam("HOSPITAL_DESCRIPTION"));

        res.add(userInfo);
        page.setRecords(res);
        msg.setResStatus(SystemConstant.UDI_SUCCESSFUL_EXECUTION);
        msg.setResMsg("登录成功");
        msg.setResData(page);
        //更新登录时间
        log.debug("HRLoginUserSvcImpl.loginCheck msg {}", msg);

        try {
            LogSaveRequest logSaveRequest = new LogSaveRequest();
            logSaveRequest.setRelatedId(0L);
            logSaveRequest.setRelatedType("login");
            logSaveRequest.setLogTitle("登录");
            logSaveRequest.setLogContent("用户名称：" + userInfo.getName());
            logSaveRequest.setOperateTime(new Date());
            logSaveRequest.setOperateType("登录");
            logSaveRequest.setOperateStatus("成功");
            requestPojo.setCustId(userInfo.getCompanyID());
            tSysLogSvc.doSaveLogin(logSaveRequest,requestPojo);
        }catch (Exception e){
            log.error("登录错误" + e.getMessage());
        }
        return msg;
    }
    /**
     * 登出
     * */
    @Override
    public void loginOut(HttpSession session,RequestPojo requestPojo) {
        if(stringRedisTemplate.hasKey(RedisKeyConstant.USER_TOKEN + ":" + requestPojo.getCustId() + ":"+ requestPojo.getCustId())){
            stringRedisTemplate.delete(RedisKeyConstant.USER_TOKEN + ":" + requestPojo.getCustId() + ":"+ requestPojo.getCustId());
        }
        try {
            LogSaveRequest logSaveRequest = new LogSaveRequest();
            logSaveRequest.setRelatedId(0L);
            logSaveRequest.setRelatedType("login");
            logSaveRequest.setLogTitle("登出");
            logSaveRequest.setLogContent("用户名称：" + requestPojo.getUserName());
            logSaveRequest.setOperateTime(new Date());
            logSaveRequest.setOperateType("登出");
            logSaveRequest.setOperateStatus("成功");
            tSysLogSvc.doSaveLogin(logSaveRequest,requestPojo);
        }catch (Exception e){
            log.error("登出错误" + e.getMessage());
        }
//        session.invalidate();
    }

    /**
     * 前端需要的结构（菜单权限及按钮权限） 2019-11-13
     * @param hrGroupMenuInfoList
     * @return
     */
    private List<SYMenuItem> makeMenuItems(List<SYMenuItem> sYMenuItem, List<SYGroupMenuInfo> hrGroupMenuInfoList){
        String CompanyID = "";
        if(Objects.nonNull(sYMenuItem) && sYMenuItem.size() > 0){
            CompanyID = hrGroupMenuInfoList.get(0).getCompanyID();
        }else {
            CompanyID = COMPANY_CODE;
        }

        String topMenuList1 = "''";
        String secondMenuList1 = "''";
        String menuList1 = "''";
        String menuList = "''";
        HashMap<String, SYMenuItem> topMenuMap = new HashMap<>();
        HashMap<String, SYMenuSubItem> subMenuMap = new HashMap<>();
        HashMap<String, SYMenuSubTitle> leafMenuMap = new HashMap<>();
        List<SYMenuItem> topMenuList = new ArrayList<>();
        List<SYMenuSubItem> subMenuList = new ArrayList<>();
        List<SYMenuSubTitle> leafMenuList = new ArrayList<>();

        for(int i = 0; i < hrGroupMenuInfoList.size(); i++){
            menuList = menuList + ",'" + hrGroupMenuInfoList.get(i).getMenuID() + "'";

//            if(!Objects.isNull(hrGroupMenuInfoList.get(i).getParentMenuID()) && hrGroupMenuInfoList.get(i).getParentMenuID().equals("0")){
//                SYMenuItem tempItem = new SYMenuItem();
//                tempItem.setIcon(hrGroupMenuInfoList.get(i).getMenuLogo());
//                tempItem.setIndex(hrGroupMenuInfoList.get(i).getMenuCode());
//                tempItem.setTitle(hrGroupMenuInfoList.get(i).getMenuDisp());
//                tempItem.setParentID(hrGroupMenuInfoList.get(i).getMenuID());
//                if(Objects.isNull(topMenuMap.get(hrGroupMenuInfoList.get(i).getMenuID()))){
//                    topMenuMap.put(hrGroupMenuInfoList.get(i).getMenuID(), tempItem);
//                }
//                if(!topMenuList.contains(tempItem)){
//                    topMenuList.add(tempItem);
//                }
//                sYMenuItem.add(tempItem);
//                topMenuList1 = topMenuList1 + ",'" + hrGroupMenuInfoList.get(i).getMenuID() + "'";
//            }else if(Objects.isNull(hrGroupMenuInfoList.get(i).getMenuCode())
//                    || StringUtils.isEmpty(hrGroupMenuInfoList.get(i).getMenuCode())){
//                SYMenuSubItem subTempItem = new SYMenuSubItem();
//                subTempItem.setRW(hrGroupMenuInfoList.get(i).getRW());
//                subTempItem.setIndex(hrGroupMenuInfoList.get(i).getMenuCode());
//                subTempItem.setTitle(hrGroupMenuInfoList.get(i).getMenuDisp());
////                if(Objects.isNull(subMenuMap.get(hrGroupMenuInfoList.get(i).getMenuID()))){
////                    subMenuMap.put(hrGroupMenuInfoList.get(i).getMenuID(), subTempItem);
////                }
//                if(!subMenuList.contains(subTempItem)){
//                    subMenuList.add(subTempItem);
//                }
//                secondMenuList1 = secondMenuList1 + ",'" + hrGroupMenuInfoList.get(i).getMenuID() + "'";
//            } else {
//                SYMenuSubTitle subTempItem = new SYMenuSubTitle();
//                subTempItem.setRW(hrGroupMenuInfoList.get(i).getRW());
//                subTempItem.setIndex(hrGroupMenuInfoList.get(i).getMenuCode());
//                subTempItem.setTitle(hrGroupMenuInfoList.get(i).getMenuDisp());
//                if(Objects.isNull(leafMenuMap.get(hrGroupMenuInfoList.get(i).getMenuID()))){
//                    leafMenuMap.put(hrGroupMenuInfoList.get(i).getMenuID(), subTempItem);
//                }
////                if(!leafMenuList.contains(subTempItem)){
////                    leafMenuList.add(subTempItem);
////                }
//                menuList1 = menuList1 + ",'" + hrGroupMenuInfoList.get(i).getMenuID() + "'";
//            }
        }



        HashMap hsMenuData = new HashMap();
        hsMenuData.put("CompanyID", CompanyID);
        hsMenuData.put("MenuIDList", menuList);
        hsMenuData.put("NOTMenuCode", "");
        hsMenuData.put("NOTParentMenuID", "0");

        List<SYmenu> sYMenus = null;
        Page page = new Page();
        sYMenus = sYmenuDao.selectListByGroup(page, hsMenuData);
        for(SYmenu symenu: sYMenus){
            SYMenuSubTitle subTempItem = new SYMenuSubTitle();
            subTempItem.setRW(getMenuRW(symenu.getMenuID(), hrGroupMenuInfoList));
            subTempItem.setIndex(symenu.getMenuCode());
            subTempItem.setTitle(symenu.getMenuDisp());
            subTempItem.setParentID(symenu.getParentMenuID());
            SYMenuSubItem subItem = subMenuMap.get(symenu.getParentMenuID());
            if(Objects.isNull(subItem)){
                subItem = getMenuSubItem(symenu, hrGroupMenuInfoList);
            }
            if(!Objects.isNull(subItem) && !subItem.getParentID().equals("0")){
                List<SYMenuSubTitle> leafMenuList1 = subItem.getSubs();
                if(Objects.isNull(leafMenuList1)){
                    leafMenuList1 = new ArrayList<>();
                }
                leafMenuList1.add(subTempItem);
                subItem.setSubs(leafMenuList1);
                subMenuMap.put(symenu.getParentMenuID(), subItem);
            } else if(Objects.isNull(subItem) || (!Objects.isNull(subItem) && subItem.getParentID().equals("0"))){
                subItem = new SYMenuSubItem();
                subItem.setParentID(symenu.getParentMenuID());
                subItem.setRW(subTempItem.getRW());
                subItem.setIndex(subTempItem.getIndex());
                subItem.setTitle(subTempItem.getTitle());
                subItem.setMenuID(symenu.getMenuID());
                subMenuMap.put(symenu.getMenuID(), subItem);
            }
            leafMenuList.add(subTempItem);
        }

        Set MenuKey = subMenuMap.keySet();
        for(int j = 0; j < MenuKey.size(); j++) {
            String strMenuKey = (String) MenuKey.toArray()[j].toString();
            String strParentID = subMenuMap.get(strMenuKey).getParentID();
            SYMenuItem menuItem = topMenuMap.get(strParentID);
            if(Objects.isNull(menuItem)){
                menuItem = getMenuItem(subMenuMap.get(strMenuKey), hrGroupMenuInfoList);
            }
            subMenuList = menuItem.getSubs();
            if(Objects.isNull(subMenuList)){
                subMenuList = new ArrayList<>();
            }
            subMenuList.add(subMenuMap.get(strMenuKey));
            menuItem.setSubs(subMenuList);
            topMenuMap.put(strParentID, menuItem);
            topMenuList.add(menuItem);

//            for (int i = 0; i < topMenuList.size(); i++){
//                if (topMenuList.get(i).getParentID().equals(strMenuKey)) {
//                    subMenuList = topMenuList.get(i).getSubs();
//                }else{
//                    hsMenuData = new HashMap();
//                    hsMenuData.put("CompanyID", CompanyID);
//                    hsMenuData.put("MenuID", strMenuKey);
//                    hsMenuData.put("ParentMenuID", "0");
//
//                    sYMenus = null;
//                    page = new Page();
//                    sYMenus = sYmenuDao.selectListByGroup(page, hsMenuData);
//
//                }
//                topMenuList.add(menuItem);
//                topMenuMap.put(strMenuKey, menuItem);
//            }
        }

        List<SYMenuItem> temp = new ArrayList<>();
        MenuKey = topMenuMap.keySet();
        for(int j = 0; j < MenuKey.size(); j++) {
            String strMenuKey = (String) MenuKey.toArray()[j].toString();
            SYMenuItem menuItem = topMenuMap.get(strMenuKey);
            if(Objects.nonNull(menuItem)) {
                List<SYMenuSubItem> menuItemSort = menuItem.getSubs().stream().sorted(Comparator.comparing(SYMenuSubItem::getMenuID)).collect(Collectors.toList());
                menuItem.setSubs(menuItemSort);
            }
            temp.add(menuItem);
        }

        return temp;
    }

    /**
     * 获取RW数据
     * @param menuID
     * @param hrGroupMenuInfoList
     * @return
     */
    private String getMenuRW(String menuID, List<SYGroupMenuInfo> hrGroupMenuInfoList){
        String menuRW = "";
        List<SYGroupMenuInfo> firstA = hrGroupMenuInfoList.stream() .filter(a -> menuID.equals(a.getMenuID())) .collect(Collectors.toList());
        if(!Objects.isNull(firstA) && firstA.size() > 0 && !Objects.isNull(firstA.get(0))) {
            menuRW = firstA.get(0).getRW();
        }

        return menuRW;
    }

    /**
     * 获取二级节点信息
     * @param sYmenu
     * @param hrGroupMenuInfoList
     * @return
     */
    private SYMenuSubItem getMenuSubItem(SYmenu sYmenu, List<SYGroupMenuInfo> hrGroupMenuInfoList){
        SYMenuSubItem menuSubItem = new SYMenuSubItem();

        HashMap hsMenuData = new HashMap();
        hsMenuData.put("CompanyID", hrGroupMenuInfoList.get(0).getCompanyID());
        hsMenuData.put("MenuID", sYmenu.getParentMenuID());
        hsMenuData.put("NOTParentMenuID", "0");

        List<SYmenu> symenu = null;
        Page page = new Page();
        symenu = sYmenuDao.selectListByGroup(page, hsMenuData);
        if(!Objects.isNull(symenu) && symenu.size() > 0){
            menuSubItem.setRW(getMenuRW(symenu.get(0).getMenuID(), hrGroupMenuInfoList));
            if(!StringUtils.isEmpty(symenu.get(0).getMenuCode())) {
                menuSubItem.setIndex(symenu.get(0).getMenuCode());
            }else{
                menuSubItem.setIndex(symenu.get(0).getMenuID());
            }
            menuSubItem.setTitle(symenu.get(0).getMenuDisp());
            menuSubItem.setParentID(symenu.get(0).getParentMenuID());
            menuSubItem.setMenuID(symenu.get(0).getMenuID());
        }else {
            menuSubItem = null;
        }

        return menuSubItem;
    }

    /**
     * 获取一级节点
     * @param sYmenu
     * @param hrGroupMenuInfoList
     * @return
     */
    private SYMenuItem getMenuItem(SYMenuSubItem sYmenu, List<SYGroupMenuInfo> hrGroupMenuInfoList){
        SYMenuItem menuItem = new SYMenuItem();

        HashMap hsMenuData = new HashMap();
        hsMenuData.put("CompanyID", hrGroupMenuInfoList.get(0).getCompanyID());
        hsMenuData.put("MenuID", sYmenu.getParentID());

        List<SYmenu> symenu = null;
        Page page = new Page();
        symenu = sYmenuDao.selectListByGroup(page, hsMenuData);
        if(!Objects.isNull(symenu.get(0))){
            menuItem.setIndex(symenu.get(0).getMenuCode());
            menuItem.setTitle(symenu.get(0).getMenuDisp());
            menuItem.setParentID(symenu.get(0).getParentMenuID());
            menuItem.setIcon(symenu.get(0).getMenuLogo());
        }

        return menuItem;
    }

    /**
     * 微信登录
     * Liby 2019-12-14
     * */
    @Override
    public Result<T> doWechatLogin(String map, RequestPojo requestPojo) {
        try {
            map = URLDecoder.decode(map, "UTF-8");
        }catch (Exception e){
            log.error("doWechatLogin error: ", e);
        }
        map = map.replaceAll("=", "");
        log.debug("HRLoginUserSvcImpl.doWechatLogin map {}", map);
        Result result = new Result();
        Page page = new Page();
        HRUserInfo userInfo = new HRUserInfo();
        String EmpNumber = ParamUtil.getParamfromObject(map, "EmpNumber");
        String UserName = ParamUtil.getParamfromObject(map, "UserName");
        String Password = ParamUtil.getParamfromObject(map, "Password");

        /**
         * 验证数据
         * */
        if(StringUtils.isEmpty(EmpNumber) || StringUtils.isEmpty(UserName)){
            result.setResStatus("E1002");
            result.setResMsg("用户名或员工编号为空，数据验证不通过！");
            return result;
        }

        HashMap<String, String> hsData = new HashMap();
//        hsData.put("UserID", EmpNumber);
//        hsData.put("UserName", UserName);

        List<SYuser> sYuser = sYuserDao.selectList(page, hsData);
        if(null == sYuser || sYuser.size() == 0) {
            result.setResStatus("E1002");
            result.setResMsg("【" + UserName + "】不存在，数据验证不通过！");
            return result;
        }

        if(!StringUtils.isEmpty(sYuser.get(0).getVldFG()) && !sYuser.get(0).getVldFG().equalsIgnoreCase("0")){
            result.setResStatus("E1002");
            result.setResMsg("用户无效，数据验证不通过！");
            return result;
        }

        PasswordDigest passwordDigest = new PasswordDigest();
        /**
         * 验证密码是否正确
         * */
        if(!Password.equals(sYuser.get(0).getPassword())){
            result.setResStatus("E1002");
            result.setResMsg("用户密码不正确，数据验证不通过！");
            return result;
        }

        log.debug("HRLoginUserSvcImpl.doWechatLogin 获取数据");
//        hsData = new HashMap();
//        hsData.put("CompanyID", sYuser.get(0).getCompanyID());
//        hsData.put("GroupID", userInfo.getUserGroupID());
//        List<PYempWages> pYempWages = null;
//        pYempWages = pYempWagesDao.selectListPK(page, hsData);

        String[] title = {"栏位1","栏位2","栏位3"};
        List<List<Object>> rows = new ArrayList<>();
        Map<String, String> hsmap = new HashMap<>();
        hsmap = JSONObject.parseObject(map, HashMap.class);
//        result = expService.doQueryPageEX(hsmap,"X-003");
        log.info("MSempInfoCtrl.doExport call doQueryPageEX result {}", result);

        if(!result.getResStatus().equals(ResStatus.STATUS_SUCCESS)){
            result.setResStatus(ResStatus.STATUS_FAILED);
            result.setResMsg(ResStatus.STATUS_FAILED_MSG);
            return result;
        }

        Map<String,String> mapSql = new HashMap<>();
        List<Map<String, String>> ret = (List<Map<String, String>>) result.getResData();
        Map<String, String> mapsql = (Map<String, String>)ret.get(0);
        Map<String, String> mapTitle = (Map<String, String>)ret.get(1);
        if(null != mapTitle && null != mapTitle.get("Title")) {
            title = mapTitle.get("Title").split(",");
        }
//        rows = expService.getExportData(mapsql);
        List<String> titles = Arrays.asList(title);

        HashMap<String, Object> recs = new HashMap<>();
        recs.put("Title", titles);
        if(Objects.nonNull(rows) && rows.size() > 0) {
            recs.put("Rows", rows.get(0));
            page.setSize(1);
        }

        //Liby 2020-05-12增加访问日志
        SYLOG sylog = new SYLOG();
        sylog.setCompanyID(COMPANY_CODE);
        sylog.setExclusiveFG("0");
        sylog.setRegisteredPerson(UserName);
        sylog.setRegisteredDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        sylog.setSPINFO("doWechatLogin");
        sylog.setNOTE(UserName +  "("+ EmpNumber + "） 登录微信工资系统。");
        sylogDao.insertRecords(sylog);

        result.setResData(page.setRecords(Arrays.asList(recs)));
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

        log.debug("HRLoginUserSvcImpl.doWechatLogin msg {}", result);

        return result;
    }


    /**
     * 微信查询工资数据
     * Liby 2020-10-25
     * */
    @Override
    public Result<T> doWechatQuery(String map, RequestPojo requestPojo) {
        try {
            map = URLDecoder.decode(map, "UTF-8");
        }catch (Exception e){
            log.error("doWechatQuery error: ", e);
        }

        map = map.replaceAll("=", "");
        log.debug("HRLoginUserSvcImpl.doWechatQuery map {}", map);
        Result result = new Result();
        Page page = new Page();
        HRUserInfo userInfo = new HRUserInfo();
        Map<String, String> hsmap = new HashMap<>();
        hsmap = JSONObject.parseObject(map, HashMap.class);

        String EmpNumber = ParamUtil.getParamfromMap(hsmap, "EmpNumber");
        String PYM = ParamUtil.getParamfromMap(hsmap, "PYM");
        /**
         * 验证数据
         * */
        if(StringUtils.isEmpty(EmpNumber) || StringUtils.isEmpty(PYM)){
            result.setResStatus("E1002");
            result.setResMsg("数据验证不通过！");
            return result;
        }

        Map<String, String> mapData = new HashMap<>();
        mapData.put("CompanyID", COMPANY_CODE);
        mapData.put("PYM", PYM);
        mapData.put("LockFlag", "1");

//        List<PYmonthlyLock> entitys;
//        ParamUtil.setPage(mapData, page);
//        entitys = entitymLockDao.selectListPK(page, mapData);
//        if(Objects.nonNull(entitys) && entitys.size() == 0){
//            result.setResStatus(ResStatus.STATUS_FAILED);
//            result.setResMsg(ResStatus.STATUS_FAILED_MSG + "：" + String.valueOf(PYM) + " 该月份在工资锁定中。");
//            return result;
//        }
//
//        String[] title = {"栏位1","栏位2","栏位3"};
//        List<List<Object>> rows = new ArrayList<>();
//        result = expService.doQueryPageEX(hsmap,"X-003");
        log.info("MSempInfoCtrl.doExport call doQueryPageEX result {}", result);

        if(!result.getResStatus().equals(ResStatus.STATUS_SUCCESS)){
            result.setResStatus(ResStatus.STATUS_FAILED);
            result.setResMsg(ResStatus.STATUS_FAILED_MSG);
            return result;
        }

        Map<String,String> mapSql = new HashMap<>();
        List<Map<String, String>> ret = (List<Map<String, String>>) result.getResData();
        Map<String, String> mapsql = (Map<String, String>)ret.get(0);
        Map<String, String> mapTitle = (Map<String, String>)ret.get(1);
//        if(null != mapTitle && null != mapTitle.get("Title")) {
//            title = mapTitle.get("Title").split(",");
//        }
//        rows = expService.getExportData(mapsql);
//        List<String> titles = Arrays.asList(title);
//
//        HashMap<String, Object> recs = new HashMap<>();
//        recs.put("Title", titles);
//        if(Objects.nonNull(rows) && rows.size() > 0) {
//            recs.put("Rows", rows.get(0));
//            page.setSize(1);
//        }

        //Liby 2020-05-12增加访问日志
        SYLOG sylog = new SYLOG();
        sylog.setCompanyID(COMPANY_CODE);
        sylog.setExclusiveFG("0");
        sylog.setRegisteredPerson(EmpNumber);
        sylog.setRegisteredDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        sylog.setSPINFO("doWechatLogin");
        sylog.setNOTE(EmpNumber +  "("+ EmpNumber + "） 查询了 " + String.valueOf(PYM) + " 工资数据。");
        sylogDao.insertRecords(sylog);

//        result.setResData(page.setRecords(Arrays.asList(recs)));
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

        return result;
    }

    @Override
    public ResultStandard loginCheckJs(String userId, HttpSession session) {
        ResultStandard msg = new ResultStandard();
        List<HRUserInfo>  res = new ArrayList<>();
        Page page = new Page();
        HRUserInfo userInfo = new HRUserInfo();
        String UserID = userId;




//        try {
//            UserID = JSON.parseObject(map).getJSONObject("data").getJSONObject("param").get("UserID").toString();
//        }catch (Exception e){
//            log.debug("HRLoginUserSvcImpl.loginCheck get UserID parameter is not found.");
//        }





        HashMap<String, String> hsData = new HashMap();
//        hsData.put("CompanyID", CompanyID);
//        hsData.put("UserID", UserID);

        List<SYuser> sYuser = sYuserDao.selectList(page, hsData);
        if(null == sYuser || sYuser.size() == 0) {
            msg.setResStatus("E1002");
            msg.setResMsg("数据库中无此用户！");
            return msg;
        }



//        if(!StringUtils.isEmpty(sYuser.get(0).getVldFG()) && !sYuser.get(0).getVldFG().equalsIgnoreCase("1")){
//            msg.setResStatus("E1002");
//            msg.setResMsg("用户无效，数据验证不通过！");
//            return msg;
//        }

        userInfo.setCompanyID(sYuser.get(0).getCompanyID());
        userInfo.setEmpNo(sYuser.get(0).getEmpNo());
        userInfo.setName(sYuser.get(0).getName());
        userInfo.setUserGroupID(sYuser.get(0).getUserGroupID());
        userInfo.setGroupName(sYuser.get(0).getUserGroupID());
        userInfo.setMailAddress(sYuser.get(0).getMailAddress());
        userInfo.setNote(sYuser.get(0).getNote());
        userInfo.setPhoneNo(sYuser.get(0).getPhoneNo());
        userInfo.setCheckMAC(sYuser.get(0).getCheckMAC());
        userInfo.setMACID(sYuser.get(0).getMACID());
        userInfo.setVldFG(sYuser.get(0).getVldFG());
        userInfo.setExclusiveFG(sYuser.get(0).getExclusiveFG());
        userInfo.setUserID(sYuser.get(0).getUserID());
//        PasswordDigest passwordDigest = new PasswordDigest();
//        userInfo.setPassword(passwordDigest.encode(sYuser.get(0).getPassword()));

        hsData = new HashMap();
        hsData.put("GroupID", userInfo.getUserGroupID());


        LoginTokenBO loginTokenBO = new LoginTokenBO();
        loginTokenBO.setUserId(userInfo.getUserID());
        loginTokenBO.setUserName(userInfo.getName());
        loginTokenBO.setAppKey("erthetitrjeoitjeotjeo");
        loginTokenBO.setRoleId(userInfo.getUserGroupID());
        JSONObject data = new JSONObject();
        data.put("token",JwtUtil.createToken(loginTokenBO));
        log.debug("HRLoginUserSvcImpl.loginCheck userInfo {}", userInfo);
        msg.setResStatus("S0000");
        msg.setResMsg("登录成功");
        msg.setResData(data);
        log.debug("HRLoginUserSvcImpl.loginCheck msg {}", msg);
        return msg;
    }
}
